package com.live.dengdengtv.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.live.dengdengtv.CustomTitleActivity;
import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.MainHallActivity;
import com.live.dengdengtv.activity.support.ProfileInfoHelper;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.LoginInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.GUserInfo;
import com.live.dengdengtv.kernel.avcontrollers.QavsdkControl;
import com.live.dengdengtv.bean.Constants;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.utils.Notice;
import com.live.dengdengtv.utils.ViewClickUtils;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMUser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

public class LoginMessageActivity extends CustomTitleActivity implements View.OnClickListener{

    private final String TAG = "LoginMessageActivity";
    private EditText verify_et;
    private EditText phone_et;

    private ProfileInfoHelper mUserInfoHelper;

//    private DialogWaiting progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginmessage, R.layout.title_custom_red);
        setDefaultTitle("短信验证码登陆");

        mUserInfoHelper = new ProfileInfoHelper(null);

        phone_et = (EditText) findViewById(R.id.phone_et);
        verify_et = (EditText) findViewById(R.id.verify_et);

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.verifyCode_bt:
                getVerifyCode();
                break;
            case R.id.next_bt:
                attemptLogin();
                break;
        }

    }


    /**
     * 跳转主界面
     */
    private void jumpIntoHomeActivity() {
        Intent intent = new Intent(this, MainHallActivity.class);
        startActivity(intent);
        setJPush();
        finish();
    }

    private void setJPush(){
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);

        CustomPushNotificationBuilder builder =
                new CustomPushNotificationBuilder(
                        this,
                        R.layout.customer_notitfication_layout,
                        R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable = R.mipmap.ic_logo;
        builder.statusBarDrawable  = R.mipmap.ic_logo;
        JPushInterface.setDefaultPushNotificationBuilder( builder);
    }


    public void getVerifyCode() {

        String phone = phone_et.getText().toString().trim();
        if(TextUtils.isEmpty(phone)){
            Notice.alert(context, "手机号不能为空!");
            return;
        }

        Map<String,String> params = new HashMap<String, String>();
        params.put("phone", phone);
        params.put("code_type", "5");
        params.putAll(AppInfo.getHeadInfo());
        requestData(NetTaskList.getVerify, params,3);
    }


    private void attemptLogin(){
        if(ViewClickUtils.isFastClick(2000)){
            return;
        }
        String phone = phone_et.getText().toString().trim();
        String verifyCode = verify_et.getText().toString().trim();

        if(TextUtils.isEmpty(phone)){
            Notice.alert(context, "手机号不能为空!");
            return;
        }
        if(TextUtils.isEmpty(verifyCode)){
            Notice.alert(context, "验证码不能为空!");
            return;
        }


        Map<String,String> params = new HashMap<String, String>();
        params.put("phone", phone);
        params.put("code", verifyCode);
        params.putAll(AppInfo.getHeadInfo());
        requestData(NetTaskList.login_code, params,0);
    }


    private void sdkLoginSucc(){
        getMyInfo();
    }
    private void sdkLoginFail(){
        Notice.alert(context, "网络错误!");
    }
    private void getMyInfo(){
        requestData(NetTaskList.get_userInfo, AppInfo.getHeadInfo(),1);
    }
    private void getRoomId(){
        NetTaskList.getInstance().getRoomId(this, 2, this);
    }

    private void getBannerList(){
        requestData(NetTaskList.get_bannerList, AppInfo.getHeadInfo(),1001);
    }

    @Override
    public boolean onResponse(SimpleInfoData response, int id) {
        if (response.result == 0) {
            if (id == 0) {
                JsonObject dataJson = response.data.getAsJsonObject();
                AppInfo.loginInfo.setUserId(dataJson.get("user_id").getAsString());
                AppInfo.loginInfo.setUserSig(dataJson.get("user_sign").getAsString());
                AppInfo.loginInfo.setUserPhone(phone_et.getText().toString().trim());
//                AppInfo.loginInfo.setUserPassword(password_et.getText().toString().trim());
                AppInfo.loginInfo.holdLoginInfo(context);

                sdkLogin(LoginInfo.getInstance().getUserId(), LoginInfo.getInstance().getUserSig());
            } else if (id == 1) {
                GUserInfo userInfo = new Gson().fromJson(response.data.getAsJsonObject(), GUserInfo.class);
                Log.e("onResponse", userInfo.toString());
                LoginInfo.getInstance().setgUserInfo(userInfo);

                mUserInfoHelper.setMyNickName(LoginInfo.getInstance().getUserNickname());
                mUserInfoHelper.setMySex(LoginInfo.getInstance().getUserSex());
                mUserInfoHelper.setMyAvator(LoginInfo.getInstance().getAvatarAddress());
                mUserInfoHelper.setMySign(LoginInfo.getInstance().getUserSign());

                getRoomId();

            } else if (id == 2) {
                int room_id = response.data.getAsJsonObject().get("room_id").getAsInt();
                Log.e("room_id", room_id + "");
                LoginInfo.getInstance().setRoomId(room_id);
                LoginInfo.getInstance().setChatRoomId(room_id + "");
                jumpIntoHomeActivity();
            }  else if(id == 3) {
                if (response.result == 0) {
                    Notice.alert(context, "验证吗已发送!");
                }
            }  else if (id == 1001) {
                JsonArray array = response.data.getAsJsonArray();
                List<String> bannerList = new ArrayList<>();
                for (int i = 0; i < array.size(); i++) {
                    bannerList.add(array.get(i).getAsJsonObject().get("advert_url").toString());
                }
                LoginInfo.getInstance().setBannerList(bannerList);
            }
        }

        return false;
    }


    /**
     * 登录imsdk
     *
     * @param identify 用户id
     * @param userSig  用户签名
     */
    private void sdkLogin(final String identify, String userSig) {

        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(Constants.SDK_APPID,user,
                userSig,//用户帐号签名，由私钥加密获得，具体请参考文档
                new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        sdkLoginFail();
                    }
                    @Override
                    public void onSuccess() {
                        startAVSDK();
                    }
                });
    }

    /**
     * 初始化AVSDK
     */
    private void startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(
                Constants.SDK_APPID, 
                ""+Constants.ACCOUNT_TYPE,
                LoginInfo.getInstance().getUserId(),
                LoginInfo.getInstance().getUserSig());
        int result = QavsdkControl.getInstance().startContext();
        Log.e(TAG,"startAVSDK=="+result);
        sdkLoginSucc();
    }

}
